package com.wsz.bot.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wsz.bot.fegin.ReceiveBotMoveClient;
import com.wsz.bot.service.BotInterface;
import com.wsz.pojo.dto.BotDto;
import com.wsz.pojo.dto.MoveDto;
import org.joor.Reflect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Random;
import java.util.UUID;
import java.util.function.Supplier;

@Component
public class Consumer extends Thread{

    private BotDto botDto;

    private static ReceiveBotMoveClient receiveBotMoveClient;

    @Autowired
    public void setReceiveBotMoveClient(ReceiveBotMoveClient receiveBotMoveClient) {
        Consumer.receiveBotMoveClient = receiveBotMoveClient;
    }

    public void startTimeOut(long time, BotDto botDto){
        this.botDto = botDto;
        this.start();
        try {
            this.join(time);//最多等待多少秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            this.interrupt();
        }
    }

    private String addBotId(String code,String uid){
        int k = code.indexOf(" implements java.util.function.Supplier<Integer>");
        return code.substring(0,k) + uid + code.substring(k);
    }

    @Override
    public void run() {
        UUID uuid = UUID.randomUUID();
        String uid = uuid.toString().substring(0, 8);

        ObjectOutputStream oos = null;
        File file = new File("input.text");
        //写入

        try {
            FileOutputStream fout = new FileOutputStream(file);
            /* -------写出->序列化------- */
            oos = new ObjectOutputStream(
                    new BufferedOutputStream(fout));

            oos.writeObject(botDto);
            oos.flush();
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                oos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try{
            Supplier<Integer> botInterface= Reflect.compile(
                    "com.wsz.bot.service.impl.Bot" + uid,
                    addBotId(botDto.getBotCode(), uid)
            ).create().get();
            System.out.println("1" + botDto.getUserId());
            MoveDto moveDto = new MoveDto();
            moveDto.setUserId(botDto.getUserId());
            moveDto.setDirection(botInterface.get());
            receiveBotMoveClient.botMove(moveDto);
        }catch (Exception e){
            System.out.println("2" + botDto.getUserId());
            MoveDto moveDto = new MoveDto();
            moveDto.setUserId(botDto.getUserId());
            moveDto.setDirection(new Random().nextInt(4));
            receiveBotMoveClient.botMove(moveDto);
            e.printStackTrace();
        }
    }
}
